package com.luqm.mall.mallsearch.service.impl;

import com.alibaba.fastjson.JSON;
import com.lqm.common.to.es.SkuEsModel;
import com.luqm.mall.mallsearch.config.MallElasticConfig;
import com.luqm.mall.mallsearch.constant.EsConstant;
import com.luqm.mall.mallsearch.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    private RestHighLevelClient esRestClient;

    @Override
    public boolean productSatusUp(List<SkuEsModel> skuEsModelLists) throws IOException {
        BulkRequest bulkRequest=new BulkRequest();
        for(SkuEsModel skuEsModel: skuEsModelLists){
            IndexRequest indexRequest=new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());
            String s = JSON.toJSONString(skuEsModel);
            indexRequest.source(s, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk=esRestClient.bulk(bulkRequest, MallElasticConfig.COMMON_OPTIONS);
        //TODO 如果批量操作出错
        boolean b=bulk.hasFailures();
        if(!b){
            List<String> collect = Arrays.stream(bulk.getItems()).map((item) -> item.getId()).collect(Collectors.toList());
            log.error("商品上架出错:{}",collect);
        }
        return b;
    }


}
